<template>
  <div
    class="gd-map-container"
    :id="props.identifier"
    @click="handleGdMaoClick"
  ></div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import AMapLoader from "@amap/amap-jsapi-loader";

defineOptions({
  name: 'GdMap'
})

interface IProp {
  identifier: String;
}
const props = defineProps<IProp>();
const emit = defineEmits(['marker-click'])
const mapIns = ref(null);

const initMap = (fn) => {
  window._AMapSecurityConfig = {
    securityJsCode: "61c20c8bb18f18b1dc705bd65b80ef29",
  };
  AMapLoader.load({
    key: "6f278b3cf94e72a588677c34e736cd92	", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.DistrictLayer"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  })
    .then((AMap) => {
      const districtLayer = new AMap.DistrictLayer.Country({
        zIndex: 10,
        SOC: "CHN",
        depth: 2,
        visible: true,
        styles: {
          // "nation-stroke": "#22ffff",
          // "coastline-stroke": [0.8, 0.63, 0.94, 1],
          // "province-stroke": "white",
          // "city-stroke": "rgba(255,255,255,0.5)", //中国特有字段
          // "fill": "#000"
        },
      });
      const defaultLayer = new AMap.createDefaultLayer({
        zooms: [3, 20], //可见级别
        visible: true, //是否可见
        opacity: 1, //透明度
        zIndex: 0, //叠加层级
      });
      mapIns.value = new AMap.Map(props.identifier, {
        // mapStyle: "amap://styles/whitesmoke", //设置地图的显示样式
        layers: [defaultLayer, districtLayer],
        center: [120.298572, 36.584355],
        // layers: [districtLayer, new AMap.TileLayer.Satellite()],
      });
      mapIns.value.setFeatures(["road", "bg", "building", "point"]); // 多个种类要素显示
      mapIns.value.on("complete", () => {
        fn && fn([defaultLayer, districtLayer]);
      });
    })
    .catch((e) => {
      console.log(e);
    });
}
const getProvinceColor = (props) => {
  var rg = 255 - Math.floor(Math.random() * 255);
  const color = "rgb(" + rg + "," + rg + ",255)";
  return color;
}
const handleGdMaoClick = () => {
  console.log("gd map click");
}
const convertCoord = (locations, type) => {
  return new Promise((resolve) => {
    AMap.convertFrom(locations, type, (status, result) => {
      if (result.info === "ok") {
        resolve(result.locations);
      }
    });
  });
}
const addMarkers = async (markerData, type) => {
  if (type) {
    const locations = await convertCoord(
      markerData.map((m) => {
        return [m.lon, m.lat];
      }),
      type
    );

    markerData.forEach((m, idx) => {
      const location = locations[idx];
      m.lon = location.lng;
      m.lat = location.lat;
    });
  }

  const markers = markerData.map((m) => {
    const marker = new AMap.Marker({
      position: new AMap.LngLat(m.lon, m.lat),
      offset: new AMap.Pixel(-10, -10),
      icon: m.icon, // 添加 Icon 图标 URL
      title: m.name || "",
      properties: m
      // extData: m.properties || {},
    });
    marker.on("click", (e) => {
      emit('marker-click', e)
    });
    return marker;
  });
  mapIns.value.add(markers);
  return markers;
}
const getMapIns = () => {
  if(mapIns.value) {
    return Promise.resolve(mapIns.value)
  }
}
const removeMarkers = (markers) => {
  markers.forEach((marker) => {
    mapIns.value.remove(marker);
  });
}
const setCenter = (centerCoord, zoomLevel) => {
  if (zoomLevel != null) {
    mapIns.value.setZoomAndCenter(zoomLevel, centerCoord);
  } else {
    mapIns.value.setCenter(centerCoord);
  }
}
const setZoomLevel = (zoomLevel) => {
  mapIns.value.setZoom(zoomLevel);
}
const clearMap = () => {
  mapIns.value && mapIns.value.clearMap();
}

let currentMarker = ref({})
const setMarkerHtml = (item) => {
  mapIns.value.remove(currentMarker.value)
  // 实例化点标记
	currentMarker.value = new AMap.Marker({
		icon: item.icon,
		position: item.position,
		content: item.content,
		offset: item.offset
	});
	
  currentMarker.value.setMap(mapIns.value);
}
defineExpose({
  initMap,
  getProvinceColor,
  convertCoord,
  addMarkers,
  getMapIns,
  removeMarkers,
  setCenter,
  setZoomLevel,
  clearMap,
  setMarkerHtml
})
</script>
<style lang="less" scoped>
.gd-map-container{
  width: 100%;
  height: 100%;
  :deep(.amap-copyright), :deep(.amap-logo){
    z-index: 1;
  }
}
</style>